package by.grsu.epam.service.entitiesservice.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import by.grsu.epam.dao.GenericDAO;
import by.grsu.epam.dao.entitiesdao.SubscriberDAO;
import by.grsu.epam.dao.entitiesdao.UserRoleDAO;
import by.grsu.epam.domain.user.UserRole;
import by.grsu.epam.domain.user.impl.Subscriber;
import by.grsu.epam.service.GenericServiceImpl;
import by.grsu.epam.service.entitiesservice.SubscriberService;
import by.grsu.epam.web.workentities.ChangePassword;

@Service
public class SubscriberServiceImpl extends GenericServiceImpl<Subscriber, Long> implements SubscriberService {
	
	@Autowired
	private SubscriberDAO subscriberDAO;
	@Autowired
	private UserRoleDAO userRoleDAO;
	

	@Override
	public GenericDAO<Subscriber, Long> getDAO() {
		return subscriberDAO;
	}

	@Override
	@Transactional
	public Subscriber findByUsername(String username) {
		return subscriberDAO.findByUsername(username);
	}
	
	@Override
	@Transactional
	public Long saveNewSubscriber(Subscriber subscriber) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		subscriber.setPassword(encoder.encode(subscriber.getPassword()));

		UserRole userRole = userRoleDAO.findByAuthority("ROLE_SUBSCRIBER");
		if (userRole == null) {
			userRole = new UserRole("ROLE_SUBSCRIBER");
		}
		subscriber.getRoles().add(userRole);

		return save(subscriber);
	}

	@Override
	@Transactional
	public Subscriber changeSubscriberInfo(Subscriber subscriber) {
		Subscriber changeSubscriber = findByUsername(subscriber.getUsername());

		// Change Subscriber Info
		changeSubscriber.setFirstname(subscriber.getFirstname());
		changeSubscriber.setLastname(subscriber.getLastname());
		
		return changeSubscriber;
	}

	@Override
	@Transactional
	public Subscriber changeSubscriberPass(String username,
			ChangePassword changePass) {
		
		Subscriber subscriber = findByUsername(username);
		
		
		if (changePass.getNewPass1().equals(changePass.getNewPass2())
				&& passwordValidate(subscriber.getUsername(), changePass.getOldPass())) {
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			subscriber.setPassword(encoder.encode(changePass.getNewPass1()));
		}
		
		return subscriber;
	}
	
	private Boolean passwordValidate(String username, String password) {
		Subscriber subscriber = subscriberDAO.findByUsername(username);
		
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		
		return encoder.matches(password, subscriber.getPassword());
	}
}
